<template>
  <div>
    <div class="search">
        <input   class="search-input" type="text":placeholder="placeholderContent"
        @focus = "handleOnfocus" @blur = "handleOnblur" v-model="keyWord"
        >
    </div>
    <div class="search-content" ref="search" v-show="keyWord">
      <ul>
        <!-- 遍历list -->
        <li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="hanleCityClick(item.name)">
          {{item.name}}
        </li>
        <!-- 根据 hasNoData 函数来判断是否显示-->
        <li class="search-item border-bottom" v-show="hasNoData">
          {{text}}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "CitySearch",
  props:{
    cities:Object
  },
  data() {
    return {
      placeholderContent:'输入城市名或拼音',
      keyWord:'',
      list:[],
      timer:null,
      text:''
    }
  },
  watch:{
      keyWord(){
        // 防抖
        if(this.timer){
          clearTimeout(this.timer);
        }
        // 没有查询时 查询个反馈框内容清空
        if(!this.keyWord){
          this.list = []
          return
        }
        this.timer = setTimeout(() => {
          // 创建一个数组
          const result = []
          // 遍历传进来的cities 得到索引
          for(let i in this.cities){
            // 遍历所有的对象
            this.cities[i].forEach((element) => {
              //查找指定字符是在字符串中的下标。在则返回所在字符串下标；不在则返回-1.
              if(element.spell.indexOf(this.keyWord) > -1 || element.name.indexOf(this.keyWord) >-1){
                // 筛选完的对象 放入数组
                result.push(element)
              }
            });
          }
          // 将数组放入list中
          this.list = result;
        },100)
      }
  },
  methods:{
    handleOnfocus(){
      this.placeholderContent = ""
    },
    handleOnblur(){
      this.placeholderContent = '输入城市名或拼音'
    },
    hanleCityClick(city){
      this.$store.commit('changeCity',city)
      // 返回主页
      this.$router.push('/')
      this.keyWord = null
    } 
  },
  updated(){
    this.scroll = new Bscroll(this.$refs.search,{click: true});
  },
  computed:{
    // 当没有匹配到数据时
    // 将data中的text 写入数据
    hasNoData(){
        if(!this.list.length){
          return this.text = '没有找到匹配数据'
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import "~@/assets/styles/varibles.less";
.search{
  height: .72rem;
  padding: 0 .1rem;
  background-color: @bacc;
  .search-input{
    width: 100%;
    height: .62rem;
    line-height: .62rem;
    padding: 0 .2rem;
    text-align: center;
    box-sizing: border-box;
    border-radius: .35rem;
    color: #666;
    font-family:@font-family
  }
}
.search-content{
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #eee;
  .search-item{
    background-color: #ffffff;
    line-height: .62rem;
    padding-left: .2rem; 
    color: #666;
  }
  .border-bottom {
    &:before {
      border-color: #ccc;
    }
  }
}
</style>
